package com.example.demo.controller.mall;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Cart;
import com.example.demo.entity.member.User;
import com.example.demo.service.shop.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Copyright (C), 2019-2019, XXX有限公司
 * FileName: CartController
 * Author:   longzhonghua
 * Date:     2019/4/13 12:30
 *
 * @Description: $description$
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
@Controller
@RequestMapping("cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @PostMapping("")
    public String save(Cart cart, HttpSession session)  throws  Exception{
        User user = (User)session.getAttribute("loginUser");
        cart.setUser_id(user.getId());
        cartService.save(cart);
        return "redirect:/cart/?userId="+cart.getUser_id();
    }

    @GetMapping("")
   // @PreAuthorize("principal.id == #userId")
    /**
    * @Description: 必须要限制登录,或者会报错Failed to evaluate expression 'principal.id.equals(#userId)'
    */
    @PreAuthorize("principal.id.equals(#userId)")
    public ModelAndView cartlist(Long userId, Principal principal) {
        List<Cart> cartList = cartService.findCartByIdNative(userId);
        ModelAndView mav = new ModelAndView("web/shop/cart/list");
        mav.addObject("cartList", cartList);
        return mav;
    }
}
